###编写一个shellException异常，返回状态码及错误详情
###编写run_command函数，实现运行shell命令功能，返回stdout
##编写上下文管理器，处理指定类型的错误码，如错误码为1则忽略次错误

from subprocess import Popen, PIPE, STDOUT
import os


def run_command(command):
    currentPath = os.path.dirname(os.path.realpath(__file__))
    p = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True, cwd=currentPath)
    output, errors = p.communicate()
    resultcode=p.returncode   ##得到执行命令的状态码
    context=bytes(errors).decode("utf-8")    ###得到错误详情
    result=bytes(output).decode("utf-8")    ###得到执行的正确结果
    if resultcode !=0:     ###如果有错误，则抛出自定义异常
        raise shellException(resultcode,context)
    return result   ###返回执行命令的结果

###shellException异常
class shellException(Exception):
    def __init__(self,code,content):
        self.code=code
        self.content=content
    def get_error_info(self):
        return [self.code,self.content]

###上下文管理器
class shellContext():
    def __init__(self,command):
        self.command=command

    def __enter__(self):
        return self

    def run_command(self):
        self.result=run_command(self.command)
        print("执行结果为:\n",self.result)

    def __exit__(self, exc_type, exc_val, exc_tb):
        print(exc_type)
        if exc_type:     ##捕捉到异常
            print("已经捕捉到异常")
            if exc_val.code!=1:
                print("错误详情:",exc_val.content)
                return True
            return False
command=input("请输入你的操作:")
with shellContext(command) as f:
    f.run_command() 
